package com.mask.im.business.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mask.im.business.model.entity.UserAuth;
import com.mask.token.model.MaskUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 自定义用户详情服务示例
 * 展示如何在用户项目中实现UserDetailsService
 *
 * @author mask
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserAuthService userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserAuth userAuth = userRepository.getOne(new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getUsername, username));

        if (userAuth == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 转换为MaskUserDetails
        MaskUserDetails userDetails = new MaskUserDetails();
        userDetails.setUserId(userAuth.getUserInfoId().longValue());
        userDetails.setUsername(userAuth.getUsername());
        userDetails.setPassword(userAuth.getPassword());
        userDetails.setEmail(userAuth.getEmail());
        userDetails.setPhone(userAuth.getPhone());
        userDetails.setNickname(userAuth.getUsername());
//        userDetails.setAvatar(userAuth.get());
        userDetails.setEnabled(true);
        userDetails.setAuthorities(getAuthorities(""));


        return userDetails;
    }

    /**
     * 将角色字符串转换为权限集合
     */
    private Collection<? extends GrantedAuthority> getAuthorities(String roles) {
        if (roles == null || roles.trim().isEmpty()) {
            return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
        }
        return Arrays.stream(roles.split(","))
                .map(role -> role.trim())
                .filter(role -> !role.isEmpty())
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());
    }
}
